<!-- Full example of using Stomp interacts with backend service. -->
<script setup lang="ts">
import { StompClientService, StompSubscriber } from 'my-stomp-helper';
import { useStompJsStore } from 'my-vue-core/stores';
import { onMounted } from 'vue';

import { useStompSubscriber } from '@/shared/composables/stompjs-composable';

const stompJsStore = useStompJsStore();

let stompSubscriber: StompSubscriber;
let subscriptionId: string;

onMounted(() => {
  // Must spawn after init.
  // stompSubscriber = StompClientService.spawn();
  stompSubscriber = useStompSubscriber();

  // stompSubscriber.subscribeOnce({
  //   destination: '/topic/greetings',
  // }).then((res) => console.dir(res));
});

function connect(): void {
  StompClientService.connect();
}

function disconnect(): void {
  StompClientService.disconnect();
}

function subscribe(): void {
  subscriptionId = stompSubscriber.subscribe({
    destination: '/topic/greetings',
    callback: (res) => {
      console.dir(res);
    },
    headers: {
      Authorization: 'Bearer token-value-goes-here',
    },
  });
}

function unsubscribe(): void {
  stompSubscriber.unsubscribe(subscriptionId);
}

function send(): void {
  // On server side destination = StompEndpointRegistry.addEndpoint + @MessageMapping in backend service.
  stompSubscriber
    .sendAndGet({
      destination: '/ws/hello',
      headers: {
        Authorization: 'Bearer token-value-goes-here',
      },
      webSocketBody: {
        payload: {
          id: 1,
          name: 'web',
        },
      },
    })
    .then((res) => {
      console.dir(res);
    });
}
</script>

<template>
  <div>
    <h2>@stomp/stompjs</h2>
  </div>
  <div>
    <h3 style="text-align: center">{{ stompJsStore.currentState }}</h3>
  </div>
  <div>
    <el-button class="full-width" @click="connect()">Connect</el-button>
  </div>
  <div>
    <el-button class="full-width" @click="disconnect()">Disconnect</el-button>
  </div>
  <div>
    <el-button class="full-width" @click="subscribe()">Subscribe</el-button>
  </div>
  <div>
    <el-button class="full-width" @click="unsubscribe()">Unsubscribe</el-button>
  </div>
  <div>
    <el-button class="full-width" @click="send()">Send</el-button>
  </div>
  <div>
    <RouterLink to="/home">Route</RouterLink>
  </div>
</template>

<style scoped></style>
